import ApiService from './api';
import { Order, PaginationParams, PaginatedResponse } from '../types';

// 订单查询参数
export interface OrderQueryParams extends PaginationParams {
  keyword?: string;
  status?: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  shopId?: string;
  userId?: string;
  paymentMethod?: string;
  startDate?: string;
  endDate?: string;
  minAmount?: number;
  maxAmount?: number;
}

// 订单更新数据
export interface OrderUpdateData {
  status?: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  trackingNumber?: string;
  shippingCompany?: string;
  notes?: string;
}

// 订单服务
export class OrderService {
  // 获取订单列表
  static async getOrders(params: OrderQueryParams): Promise<PaginatedResponse<Order>> {
    return await ApiService.get<PaginatedResponse<Order>>('/admin/orders', params);
  }
  
  // 获取订单详情
  static async getOrder(id: string): Promise<Order> {
    return await ApiService.get<Order>(`/admin/orders/${id}`);
  }
  
  // 更新订单
  static async updateOrder(id: string, data: OrderUpdateData): Promise<Order> {
    return await ApiService.put<Order>(`/admin/orders/${id}`, data);
  }
  
  // 更新订单状态
  static async updateOrderStatus(id: string, status: Order['status']): Promise<Order> {
    return await ApiService.patch<Order>(`/admin/orders/${id}/status`, { status });
  }
  
  // 批量更新订单状态
  static async updateOrdersStatus(ids: string[], status: Order['status']): Promise<void> {
    await ApiService.post('/admin/orders/batch-status', { ids, status });
  }
  
  // 取消订单
  static async cancelOrder(id: string, reason?: string): Promise<Order> {
    return await ApiService.post<Order>(`/admin/orders/${id}/cancel`, { reason });
  }
  
  // 发货
  static async shipOrder(id: string, data: {
    trackingNumber: string;
    shippingCompany: string;
    notes?: string;
  }): Promise<Order> {
    return await ApiService.post<Order>(`/admin/orders/${id}/ship`, data);
  }
  
  // 确认收货
  static async confirmDelivery(id: string): Promise<Order> {
    return await ApiService.post<Order>(`/admin/orders/${id}/confirm-delivery`);
  }
  
  // 申请退款
  static async requestRefund(id: string, data: {
    reason: string;
    amount: number;
    items?: string[];
  }): Promise<any> {
    return await ApiService.post(`/admin/orders/${id}/refund`, data);
  }
  
  // 处理退款
  static async processRefund(id: string, data: {
    approved: boolean;
    reason?: string;
    amount?: number;
  }): Promise<any> {
    return await ApiService.post(`/admin/orders/${id}/process-refund`, data);
  }
  
  // 获取订单统计
  static async getOrderStats(period: 'day' | 'week' | 'month' = 'month'): Promise<{
    totalOrders: number;
    totalRevenue: number;
    averageOrderValue: number;
    ordersByStatus: Record<string, number>;
    revenueData: Array<{
      date: string;
      revenue: number;
      orders: number;
    }>;
  }> {
    return await ApiService.get('/admin/orders/stats', { period });
  }
  
  // 获取待处理订单
  static async getPendingOrders(params: PaginationParams): Promise<PaginatedResponse<Order>> {
    return await ApiService.get<PaginatedResponse<Order>>('/admin/orders/pending', params);
  }
  
  // 获取今日订单
  static async getTodayOrders(params: PaginationParams): Promise<PaginatedResponse<Order>> {
    return await ApiService.get<PaginatedResponse<Order>>('/admin/orders/today', params);
  }
  
  // 获取热销商品（基于订单）
  static async getTopSellingProducts(period: 'day' | 'week' | 'month' = 'month', limit: number = 10): Promise<Array<{
    productId: string;
    productName: string;
    totalSold: number;
    totalRevenue: number;
  }>> {
    return await ApiService.get('/admin/orders/top-products', { period, limit });
  }
  
  // 获取订单地域分布
  static async getOrdersByRegion(period: 'day' | 'week' | 'month' = 'month'): Promise<Array<{
    province: string;
    city: string;
    orderCount: number;
    revenue: number;
  }>> {
    return await ApiService.get('/admin/orders/by-region', { period });
  }
  
  // 导出订单数据
  static async exportOrders(params: OrderQueryParams): Promise<void> {
    await ApiService.download('/admin/orders/export', 'orders.xlsx');
  }
  
  // 获取订单物流信息
  static async getOrderTracking(id: string): Promise<{
    trackingNumber: string;
    shippingCompany: string;
    status: string;
    trackingInfo: Array<{
      time: string;
      location: string;
      description: string;
    }>;
  }> {
    return await ApiService.get(`/admin/orders/${id}/tracking`);
  }
  
  // 获取订单支付信息
  static async getOrderPayment(id: string): Promise<{
    paymentMethod: string;
    paymentStatus: string;
    transactionId: string;
    paidAt: string;
    amount: number;
    paymentDetails: any;
  }> {
    return await ApiService.get(`/admin/orders/${id}/payment`);
  }
  
  // 重新发送订单通知
  static async resendOrderNotification(id: string, type: 'email' | 'sms'): Promise<void> {
    await ApiService.post(`/admin/orders/${id}/resend-notification`, { type });
  }
  
  // 获取订单时间线
  static async getOrderTimeline(id: string): Promise<Array<{
    time: string;
    action: string;
    description: string;
    operator?: string;
  }>> {
    return await ApiService.get(`/admin/orders/${id}/timeline`);
  }
  
  // 添加订单备注
  static async addOrderNote(id: string, note: string): Promise<void> {
    await ApiService.post(`/admin/orders/${id}/notes`, { note });
  }
  
  // 获取订单备注
  static async getOrderNotes(id: string): Promise<Array<{
    id: string;
    note: string;
    createdBy: string;
    createdAt: string;
  }>> {
    return await ApiService.get(`/admin/orders/${id}/notes`);
  }
  
  // 计算订单利润
  static async calculateOrderProfit(id: string): Promise<{
    revenue: number;
    cost: number;
    profit: number;
    profitMargin: number;
  }> {
    return await ApiService.get(`/admin/orders/${id}/profit`);
  }
}

export default OrderService;
